package com.edz.dudumifi.event;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.edawtech.module.AskMsg;
import com.edawtech.module.AskParams;
import com.edz.NettyClientBootstrap;
import com.edz.dudumifi.base.Config;
import com.edz.dudumifi.utils.PreferencesUtils;

import java.util.Map;

import io.netty.channel.socket.SocketChannel;

/**
 * Created by ganshh.gan on 2018/5/16.
 */
public class SendMsgThread extends Thread {
    private static final String TAG = "SendMsgThread";
    private String msg;
    private Context context;

    public SendMsgThread(Context context, String msg) {
        this.msg = msg;
        this.context = context;
    }

    @Override
    public void run() {
        super.run();
        String imei = null;
        SocketChannel channel = null;
        while (true) {
            imei = PreferencesUtils.getString(context, Config.IMEI);

            if (imei != null)
                channel = NettyClientBootstrap.getSocketChannel();

            if (channel != null)
                break;

        }

        sendMsg(addImei(imei, msg));
    }

    private String addImei(String imei, String msg) {
        Map map = JSONObject.parseObject(msg.trim(), Map.class);
        map.put("IMEI1", imei);
        return JSONObject.toJSON(map).toString();
    }

    private void sendMsg(String msg) {
        Log.i(TAG, "发送数据" + msg);
        AskMsg askMsg = new AskMsg();
        AskParams askParams = new AskParams();
        askParams.setContent(msg);
        askMsg.setParams(askParams);
        NettyClientBootstrap.getBootstrap().getSocketChannel().writeAndFlush(askMsg);
    }
}
